package deleteBook;

import libraryRun.MainFrame;
import mySQLServer.Link;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DeleteBook extends JFrame {
    private DeleteBook myDeleteBook;
    public DeleteBook(){
        super("图书修改界面");
        myDeleteBook=this;
    }

    public void delete(MainFrame myJFrame){
        setLayout(null);
        Container container=this.getContentPane();
        setSize(1200,650);

        //面板
        JPanel p1=new JPanel(new FlowLayout(FlowLayout.CENTER));
        JPanel p2=new JPanel(new FlowLayout(FlowLayout.CENTER,50,25));
        JPanel p3=new JPanel(new BorderLayout());

        //文本行
        JTextField field1=new JTextField(15);
        JTextField field2=new JTextField(15);

        //按钮
        JButton button1=new JButton("删 除");
        JButton button2=new JButton("取 消");

        //标签
        JLabel label=new JLabel("图 书 删 除");
        JLabel label1=new JLabel("图 书 名");
        JLabel label2=new JLabel("图 书 Id");

        //表头
        String [] tableHeader={"图书名","图书Id","价格","出版社","作者"};
        Object[][] tableData=new Object[50][5];
        JTable jTable=new JTable(tableData,tableHeader);

        //滚动框
        JScrollPane jScrollPane=new JScrollPane(jTable);

        //颜色
        Color color1=new Color(50, 176,255);
        Color color2=new Color(87, 169, 140);
        Color color3=new Color(203, 26, 40);
        Color color4=new Color(13, 50, 197,225);

//        //设置颜色
//        p1.setBackground(color1);
//        p2.setBackground(color1);
//        p3.setBackground(color2);

        //字体
        Font font1=new Font("宋体",Font.BOLD,45);
        Font font2=new Font("宋体",Font.BOLD,30);
        Font font3=new Font("宋体",Font.BOLD,15);
        Font font4=new Font("宋体",Font.BOLD,14);


        //设置字体
        label.setFont(font1);
        label1.setFont(font2);
        label2.setFont(font2);
        field1.setFont(font3);
        field2.setFont(font3);

        //设置位置
        p1.setBounds(220,20,750,120);
        p2.setBounds(200,250,400,170);
        p3.setBounds(650,230,430,230);

        //表头设置
        jTable.getTableHeader().setResizingAllowed(false); //用户不可以通过拖拉表头间调整各列大小
        jTable.getTableHeader().setReorderingAllowed(false); //用户不可以通过拖动表头以重新排列各列
        jTable.getTableHeader().setFont(font3);
        jTable.getTableHeader().setForeground(color3);

        //表格设置
        jTable.setRowHeight(20); //设置行高
        jTable.setFont(font4);
        jTable.setForeground(color4);
        jTable.setSelectionForeground(color3); //设置被选中的行前景(字体颜色)
        jTable.setSelectionBackground(color2); //设置被选中的行背景
        jTable.getColumnModel().getColumn(1).setPreferredWidth(40); //先获取到某列返回一个TableCoumn 设置列宽
        jTable.getColumnModel().getColumn(2).setPreferredWidth(45);

        //设置大小
        label.setPreferredSize(new Dimension(700,120));
        label1.setPreferredSize(new Dimension(150,30));
        label2.setPreferredSize(new Dimension(150,30));
        button1.setPreferredSize(new Dimension(100,30));
        button2.setPreferredSize(new Dimension(100,30));

        //设置对其方式
        label.setHorizontalAlignment(JLabel.CENTER);

        //监听器
        ImageIcon imageIcon1=new ImageIcon("icon/imageIcon6.jpg");
        imageIcon1.setImage(imageIcon1.getImage().getScaledInstance(50,45,Image.SCALE_AREA_AVERAGING));
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(field1.getText().equals("")||field2.getText().equals("")){
                    JOptionPane.showMessageDialog(myDeleteBook,"请输入完整图书信息","输入确认",1,imageIcon1);
                    return;
                }
                Link link=new Link();
                String sql="delete from [books] where bookName='"+field1.getText()+"' and bookId="+field2.getText();
                String sql1="delete from [book_user] where bookName='"+field1.getText()+"' and bookId="+field2.getText();
                String isExisted="select * from [books] where bookName='"+field1.getText()+"' and bookId="+field2.getText();
                try{
                    if(JOptionPane.showConfirmDialog(myDeleteBook,"确认删除吗？","确认删除",JOptionPane.YES_NO_CANCEL_OPTION,1,imageIcon1)==0){
                        Connection con = link.linkDatebase();
                        int result=deleteBook(con,sql,sql1,isExisted);
                        if(result==0){
                            JOptionPane.showMessageDialog(myDeleteBook,"bookName和bookId不匹配！","信息匹配",1,imageIcon1);
                        }
                        else if(result==1){
                            JOptionPane.showMessageDialog(myDeleteBook,"删除成功！","确认删除",1,imageIcon1);
                            showBooks(con,jTable);
                        }
                        else{
                            JOptionPane.showMessageDialog(myDeleteBook,"仍有书籍未归还，删除失败！","确认删除",1,imageIcon1);
                        }
                        link.closeDatebase(con);
                    }

                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                } catch (ClassNotFoundException classNotFoundException) {
                    classNotFoundException.printStackTrace();
                }
            }
        });

        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                myJFrame.setVisible(true);
                dispose();
            }
        });

        myDeleteBook.addWindowListener(new WindowListener() {

            public void windowOpened(WindowEvent e) {
                Link link=new Link();
                try{
                    Connection con = link.linkDatebase();
                    showBooks(con,jTable);
                    link.closeDatebase(con);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                } catch (ClassNotFoundException classNotFoundException) {
                    classNotFoundException.printStackTrace();
                }
            }

            public void windowClosing(WindowEvent e) {
                myJFrame.setVisible(true);
            }

            public void windowClosed(WindowEvent e) {

            }

            public void windowIconified(WindowEvent e) {

            }

            public void windowDeiconified(WindowEvent e) {

            }

            public void windowActivated(WindowEvent e) {

            }

            public void windowDeactivated(WindowEvent e) {

            }
        });

        //放入面板
        p1.add(label);

        p2.add(label1);
        p2.add(field1);
        p2.add(label2);
        p2.add(field2);
        p2.add(button1);
        p2.add(button2);

        p3.add(jScrollPane);

        //放入容器
        container.add(p1);
        container.add(p2);
        container.add(p3);

        setIconImage((new ImageIcon("icon/imageIcon5.jpg")).getImage());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        setVisible(true);
    }


    public void showBooks (Connection con,JTable jTable) throws ClassNotFoundException, SQLException {
        int sum=0;
        String sql="select * from [books]";
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery(sql);
        while(rs.next()){
            jTable.getModel().setValueAt(rs.getString("bookName"),sum,0);
            jTable.getModel().setValueAt(rs.getString("bookId"),sum,1);
            jTable.getModel().setValueAt(rs.getString("price"),sum,2);
            jTable.getModel().setValueAt(rs.getString("publisher"),sum,3);
            jTable.getModel().setValueAt(rs.getString("author"),sum,4);
            sum++;
        }
    }

    public int  deleteBook(Connection con,String sql,String sql1,String isExisted) throws ClassNotFoundException,SQLException{
        int flag=0;
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery(isExisted);
        while(rs.next()){
            flag=1;
            if(rs.getInt("booksCount")!=rs.getInt("remainedCount"))
                return flag=2;
        }
        if(flag==1){
            stmt.executeUpdate(sql1);
            stmt.executeUpdate(sql);
        }
        return flag;
    }

}
